package me.flyray.admin.rest;

import me.flyray.admin.biz.Kaptcha;
import me.flyray.admin.rpc.service.PermissionService;
import me.flyray.admin.vo.UserVo;
import me.flyray.auth.client.annotation.IgnoreUserToken;
import me.flyray.auth.client.feign.ServiceAuthFeign;
import me.flyray.auth.common.config.UserAuthConfig;
import me.flyray.auth.common.user.UserInfo;
import me.flyray.auth.common.vo.JwtAuthenticationResponse;
import me.flyray.common.exception.ApiException;
import me.flyray.common.msg.BaseApiResponse;
import me.flyray.common.msg.ResponseCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: bolei
 * @date: 15:24 2019/1/6
 * @Description: 运营后台授权处理
 */

@RestController
@RequestMapping("auth")
@Slf4j
public class AuthController {

    @Autowired
    protected HttpServletRequest request;
    @Autowired
    private UserAuthConfig userAuthConfig;
    @Value("${jwt.token-header}")
    private String tokenHeader;
    @Autowired
    private Kaptcha kaptcha;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private ServiceAuthFeign authFeign;

    /**
     * 所有运营后台、商户、平台管理员登录授权接口
     * @return
     * @throws Exception
     */
    @IgnoreUserToken
    @RequestMapping(value = "token", method = RequestMethod.POST)
    public BaseApiResponse createAuthenticationToken(@RequestParam String grant_type,
                                                         @RequestBody UserVo user) throws Exception {
        log.info("请求的grant_type...{}",grant_type);
        if (!StringUtils.hasText(grant_type)) {

        }
        //用户名密码模式
        if ("password".equals(grant_type)) {
            log.info(user.getUsername()+" require logging...");
            UserInfo userInfo = permissionService.validate(user.getUsername(),user.getPassword());
            BaseApiResponse<JwtAuthenticationResponse> response = authFeign.getAdminUserToken(userInfo);
            if (!response.getSuccess()){
                throw new ApiException(response.getCode(),response.getMessage());
            }
            return BaseApiResponse.newSuccess(response.getData());
        }else if ("client_credentials".equals(grant_type)){
            //客户端模式 app key 是 第三方用户唯一凭证 app secret 是 第三方用户唯一凭证密钥
            return BaseApiResponse.newSuccess(null);
        }else {
            return BaseApiResponse.newFailure(ResponseCode.CUST_NOTEXIST);
        }
    }

    /**
     * 退出登陆
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "logout", method = RequestMethod.POST)
    public BaseApiResponse logout() throws Exception {
        log.info("destroy token...{}");
        authFeign.verify(request.getHeader(userAuthConfig.getTokenHeader()));
        return BaseApiResponse.newSuccess();
    }



    /*@RequestMapping(value = "refresh", method = RequestMethod.GET)
    public BaseApiResponse refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws Exception {
        String token = request.getHeader(tokenHeader);
        Map<String, Object> refreshedToken = authFeign.refresh(token);
        return BaseApiResponse.newSuccess(refreshedToken);
    }

    @RequestMapping(value = "verify", method = RequestMethod.GET)
    public BaseApiResponse<?> verify() throws Exception {
        authFeign.verify(request.getHeader(userAuthConfig.getTokenHeader()));
        return BaseApiResponse.newSuccess();
    }*/

    /**
     * 获取图形验证码
     * */
    @IgnoreUserToken
    @GetMapping("/identifyingCode")
    public void render(@RequestParam("date") String date) {
        kaptcha.render();
    }


    /**
     * 根据用户手机号发送登录验证码
     * 1、先判断手机号是否存在
     * 2、发送短信验证码
     * 3、Redis保存短信验证码
     * @author centerroot
     * @time 创建时间:2018年11月19日下午4:50:49
     * @param req
     * @return
     */
    /*@RequestMapping(value = "/sendCodeByPhone", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> sendCodeByPhone(@RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception {
        Map<String, Object> resp = authService.sendCodeByPhone(authenticationRequest);
        return resp;
    }*/

    /**
     * 手机号登录接口
     * 1、校验短信验证码
     * 2、返回token
     * @author centerroot
     * @time 创建时间:2018年11月19日下午5:32:45
     * @param req
     * @return
     */
    /*@RequestMapping(value = "/loginByPhone", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> loginByPhone(@RequestBody JwtAuthenticationRequest authenticationRequest) throws Exception {
        Map<String, Object> resp = authService.loginByPhone(authenticationRequest);
        return resp;
    }*/

}
